package com.raycloud.erp.omll.provider.utils;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * @Author: ruanyaguang
 * @Date : 2018/12/17
 * @Info : 多平台通用字符串工具类
 */
public class PlatformStringUtils {
    private static final Pattern UTF8MB4_PATTERN = Pattern.compile("\\\\u([0-9a-zA-Z]{4})\\\\u([0-9a-zA-Z]{4})");

    /**
     * 替换utf8mb字符为uxxxxuxxxx格式
     *
     * @param str
     * @return
     */
    public static String replaceUtf8mb4(String str) {
        if (null == str) {
            return str;
        }
        final int LAST_BMP = 0xFFFF;
        StringBuilder sb = new StringBuilder(str.length());
        for (int i = 0; i < str.length(); i++) {
            int codePoint = str.codePointAt(i);
            if (codePoint < LAST_BMP) {
                sb.appendCodePoint(codePoint);
            } else {
                if (i < str.length() - 1) {
                    sb.append("\\u").append(Integer.toHexString(str.charAt(i)))
                        .append("\\u").append(Integer.toHexString(str.charAt(i + 1)));
                    i++;
                } else {
                    // 逻辑到这里说明存在尾部单字符utf8mb，直接去除
                }
            }
        }
        return sb.toString();
    }

    /**
     * 将uxxxxuxxxx格式字符串还原成utf8mb字符
     *
     * @param str
     * @return
     */
    public static String regainUtf8mb4(String str) {
        if (null == str) {
            return str;
        }
        Matcher matcher = UTF8MB4_PATTERN.matcher(str);
        StringBuffer sb = new StringBuffer(str.length());
        while (matcher.find()) {
            matcher.appendReplacement(sb, new String(new char[]{(char) Integer.parseInt(matcher.group(1), 16),
                (char) Integer.parseInt(matcher.group(2), 16)}));
        }
        matcher.appendTail(sb);
        return sb.toString();
    }
}